<?php

class Accident_recordController extends CController
{
	const PAGE_SIZE=10;

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction='create';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			array('application.filters.LoginFilter'),
			array('application.filters.AuthFilter'),
		);
	}

	/**
	 * Shows a particular model.
	 */
	public function actionShow()
	{
		$model=$this->loadAccident_record();
		$detail_models=$this->loadAccident_cost_detail();
		$this->render('show',array('model'=>$model,'detail_models'=>$detail_models));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionCreate(){
		
		$model=new Accident_record;
		$detail_models=array(new Accident_cost_detail);
		if(isset($_POST['Accident_record'])){//将所有费用赋值 并且验证
			$model->attributes=$_POST['Accident_record'];
			$details=$_POST['detail'];
			$create=true;
			foreach($details as $n=>$val){
				$detail_model=new Accident_cost_detail;
				$detail_model->attributes=$val;
				$detail_models[$n]=$detail_model;
				$create=$detail_model->validate()==true?$create:false;
			}
			$create=$model->validate()==true?$create:false;//验证事故信息
			if($create){//全部验证通过  添加数据库 启动事务
				$tran=$model->getDbConnection()->beginTransaction();
				try{
					$model->save(false);
					foreach($detail_models as $val){
						$val->fk_accident_id=$model->id;
						$val->save(false);
					}
					$tran->commit();
				}
				catch(Exception $e){
					$tran->rollBack();
					throw $e;
				}
				//$this->render('show',array('model'=>$model,'detail_models'=>$detail_models,'ret'=>'create','info'=>'添加成功！'));
				//return;
				$this->redirect(array('show','id'=>$model->id,'ret'=>'create','ok'=>'0'));
			}
		}
		$this->render('create',array('model'=>$model,'detail_models'=>$detail_models));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadAccident_record();
		$detail_models=$this->loadAccident_cost_detail();
		if(isset($_POST['Accident_record'])){//将所有费用赋值 并且验证
			$model->attributes=$_POST['Accident_record'];
			$details=$_POST['detail'];
			$details_sum=count($details);
			$detail_models_sum=count($detail_models);
			$update=true;
			if($details_sum==$detail_models_sum){//费用信息数量没变
				foreach($details as $n=>$val){
					$detail_model=$detail_models[$n];
					$detail_model->attributes=$val;
					$update=$detail_model->validate()==true?$update:false;
				}
			}
			else if($details_sum>$detail_models_sum){//费用信息数量增加
				foreach($details as $n=>$val){
					$detail_model=isset($detail_models[$n])?$detail_models[$n]:new Accident_cost_detail;
					$detail_model->attributes=$val;
					$update=$detail_model->validate()==true?$update:false;
					$detail_models[$n]=$detail_model;
				}
			}
			else if($details_sum<$detail_models_sum){//费用信息数量减少
				foreach($detail_models as $n=>$val){
					if(isset($details[$n])){
						$val->attributes=$details[$n];
						$update=$val->validate()==true?$update:false;
					}
					else
						$val->state=1;
				}
			}
			$update=$model->validate()==true?$update:false;//验证事故信息
			if($update){//全部验证通过  添加数据库
				$tran=$model->getDbConnection()->beginTransaction();
				try{
					$model->save(false);
					foreach($detail_models as $val){
						$val->fk_accident_id=$model->id;
						$val->save(false);
						if($val->state==1) unset($detail_models[$n]);
					}
					$tran->commit();
				}
				catch(Exception $e){
					$tran->rollBack();
					throw $e;
				}
				//$this->render('show',array('model'=>$model,'detail_models'=>$detail_models,'ret'=>'admin','info'=>'更新成功！'));
				//return;
				$this->redirect(array('show','id'=>$model->id,'ret'=>'admin','ok'=>'1')+$_GET);
			}
		}
		$this->render('update',array('model'=>$model,'detail_models'=>$detail_models));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete()
	{
		if(isset($_GET['id'])){
			$accident_record=Accident_record::model();
			$accident_cost_detail=Accident_cost_detail::model();
			$tran=$accident_record->getDbConnection()->beginTransaction();
			try{
				$accident_record->updateByPk($_GET['id'],array('state'=>1));
				$accident_cost_detail->updateAll(array('state'=>1),array('condition'=>'fk_accident_id='.$_GET['id']));
				$tran->commit();
			}
			catch(Exception $e){
				$tran->rollBack();
				throw $e;
			}
			unset($_GET['id']);
			$this->redirect(array('admin')+$_GET);
		}
		else
			throw new CHttpException(400,'无法获得要删除的信息ID!');
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{	
		$this->search(false);
	}
	
	public function actionSearch(){
		$this->search();
	}
	
	private function search($method=true){
		$criteria=new CDbCriteria();
		$criteria->join='INNER JOIN trucks ON trucks.id=accident_record.fk_truck_id
						INNER JOIN drivers ON drivers.id=accident_record.fk_driver_id';
		$criteria->select='trucks.plate_no as plate_no,trucks.property_owner as property_owner,drivers.name as driver_name,accident_record.*';
		$criteria->addCondition('accident_record.state=0');
		$blur=true;
		if(Yii::app()->getRequest()->isPostRequest){
			if(isset($_POST['keys'])){//页面传来的搜索关键字数组
				$_GET['keys']=$_POST['keys'];
			}
		}
		if(isset($_GET['keys'])){
			if(isset($_GET['keys']['blur'])&&$_GET['keys']['blur']=='0') $blur=false;
			foreach($_GET['keys'] as $key=>$val){
				if(trim($val)=='')
					unset($_GET['keys'][$key]);
				else if($key=='s_date'){//时间查询
					$criteria->addCondition("accident_date>='{$val}'");
				}
				else if($key=='e_date'){//时间查询  
					$criteria->addCondition("accident_date<'".date('Y-m-d',strtotime($val." +1days"))."'");
				}	
				else if($key!='blur'){//按照模糊或精确查询
					$blur?$criteria->addSearchCondition($key,$val):$criteria->addCondition("{$key}='{$val}'");
				}
			}
		}
		if(isset($_GET['excel']))
			$this->toExcel($criteria);
		else	
			$this->toAdminPage($criteria,$method);
	}
	
	public function toAdminPage($criteria,$method){
		$model=Accident_record::model();
		$pages=new CPagination($model->count($criteria));
		$pages->pageSize=Yii::app()->params['page_size']['accident_record'];
		$pages->applyLimit($criteria);
		
		$sort=new CSort('Accident_record');
		$sort->attributes=array_merge($model->attributeNames(),array('driver_name','plate_no','property_owner'));
		$sort->applyOrder($criteria);
		$models=$model->findAll($criteria);

		$this->render('admin',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
			'search'=>$method,
		));
	}
	
	public function toExcel($criteria){
		$model=Accident_record::model();
		$sort=new CSort('Accident_record');
		$sort->attributes=array_merge($model->attributeNames(),array('driver_name','plate_no','property_owner'));
		$sort->applyOrder($criteria);
		$models=$model->findAll($criteria);

		$atrr_names=$model->attributeLabels();
		$excel_names=$model->excelAttributes();$end_cell=end($excel_names);
		$tab_name='交通事故记录';
		
		require_once './protected/extensions/excel/PHPExcel.php';
		require_once './protected/extensions/excel/PHPExcel/IOFactory.php';
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->setActiveSheetIndex(0)->setTitle($tab_name);
		$objPHPExcel->getActiveSheet()->mergeCells('A1:'.$end_cell[0].'1');
		$objPHPExcel->getActiveSheet()->setCellValue('A1',$tab_name);
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(15);
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal('center');
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
		$objPHPExcel->getActiveSheet()->setCellValue('A2','序号');
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
		$objPHPExcel->getActiveSheet()->freezePane('A3');//标题栏 冻结窗口
		foreach($excel_names as $attr=>$val){//创建标题
			$objPHPExcel->getActiveSheet()->setCellValue($val[0].'2',$atrr_names[$attr]);
			$objPHPExcel->getActiveSheet()->getColumnDimension($val[0])->setWidth($val[1]);
		}
		$row_index=3;//行索引 数据从3开始 例如A从A3开始添加数据
		foreach($models as $n=>$model){
			$objPHPExcel->getActiveSheet()->setCellValue('A'.($n+$row_index),$n+1);
			foreach($excel_names as $attr=>$val){//双循环，根据model内设置进行数据导出
				$value=$model->$attr;
				if(isset($val[2]))//值->字符串 转换
					$value=$model->$val[2]();
				$objPHPExcel->getActiveSheet()->setCellValue($val[0].($n+$row_index),$value);
			}
		}
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename='.iconv("utf-8", "gb2312", $tab_name.'.xls'));
		header('Cache-Control: max-age=0');
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadAccident_record($id=null)
	{
		if($id!==null || isset($_GET['id'])){
				$criteria=new CDbCriteria();
				$criteria->join='INNER JOIN trucks ON trucks.id=accident_record.fk_truck_id
						INNER JOIN drivers ON drivers.id=accident_record.fk_driver_id';
				$criteria->select='trucks.plate_no as plate_no,trucks.property_owner as property_owner,drivers.name as driver_name,accident_record.*';
				$criteria->addCondition('accident_record.id='.($id!==null ? $id : $_GET['id']));
				$this->_model=Accident_record::model()->find($criteria);
			}
		return $this->_model;
	}

	public function loadAccident_cost_detail($id=null)
	{		
		$models;
		if($id!==null || isset($_GET['id']))
			$models=Accident_cost_detail::model()->findAllByAttributes(array('fk_accident_id'=>($id!==null ? $id : $_GET['id']),'state'=>0));
		if($models===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $models;
	}
}
